<template>
  <CommonPage>
    <template #action>
      <n-button v-permission="'AddGoods'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        创建商品
      </n-button>
    </template>

    <MeCrud ref="$table" v-model:query-items="queryItems" :scroll-x="1200" :columns="columnFields" :get-data="api.read">
      <MeQueryItem label="商品名" :label-width="50">
        <n-input v-model:value="queryItems.name" type="text" placeholder="请输入商品名" clearable />
      </MeQueryItem>

      <MeQueryItem label="审核状态" :label-width="80">
        <n-select v-model:value="queryItems.status" clearable label-field="name" value-field="id"
          :options="statusOptions" />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="1020px">
      <n-form ref="modalFormRef" label-placement="left" label-align="right" :label-width="140" :model="modalForm"
        :disabled="modalAction === 'view'">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi v-for="field in formFields" :key="field.key" :span="field.span || 12" :label="field.title"
            :disabled="modalAction !== 'add'" label-width="100px">
            <n-select v-if="field.options" v-model:value="modalForm[field.key]" :multiple="field.multiple"
              :options="field.isRemoteOptions ? remoteOptions[field.key] : field.options" label-field="name"
              value-field="id" clearable filterable />
            <n-upload v-else-if="field.isImage" :action="`/api/upload`" list-type="image-card"
              :on-before-upload="onBeforeUpload" :default-file-list="modalAction === 'setGoods' &&
                modalForm[field.key]?.split(',')?.map(url => ({
                  id: url,
                  name: url,
                  url: url,
                  status: 'finished',
                })) || []
                " :max="5" @finish="(e) => onFinish(e, field.key)"
                @remove="e => onRemove(e, field.key)">
              点击上传
            </n-upload>
            <n-switch v-else-if="field.type === 'bool'" v-model:value="modalForm[field.key]" />
            <n-date-picker v-else-if="['datetime', 'date', 'time'].includes(field.type)"
              v-model:value="modalForm[field.key]" :type="field.type" :value-format="field.type === 'datetime'
                ? 'yyyy-MM-dd HH:mm:ss'
                : field.type === 'date'
                  ? 'yyyy-MM-dd'
                  : 'HH:mm:ss'
                " clearable />
            <n-divider v-else-if="field.isFirst">{{ field.spanText }}</n-divider>
            <n-input v-else :type="field.isInputArea ? 'textarea' : ''" v-model:value="modalForm[field.key]" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton } from 'naive-ui'
import { MeCrud, MeQueryItem, MeModal } from '@/components'
import { useCrud } from '@/composables'
import api, { genColumns, statusOptions } from './api'
import dayjs from 'dayjs'
import { request } from '@/utils'

defineOptions({ name: 'UserMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
const remoteOptions = ref({
  goodsUserRelate: []
})

onMounted(() => {
  getUserList()
  $table.value?.handleSearch()
})

const tempColumns = genColumns({})
let count = 1
const initForm = tempColumns
  .filter((i) => i.isForm)
  .reduce((pre, cur) => {
    pre[cur.key] = cur.options
      ? undefined
      : ['datetime', 'date', 'time'].includes(cur.type)
        ? dayjs().valueOf()
        : `${count++}`
    return pre
  }, {})

const getUserList = async (keyWord = '') => {
  const { data } = await request.post('/user/list', {
    pageNo: 1,
    pageSize: 100,
    userType: 0,
  })
  remoteOptions.value['goodsUserRelate'] = data.records.map(i => ({ name: i.userName, id: i.id }))
}

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: '商品',
  initForm,
  doCreate: api.create,
  doDelete: api.delete,
  doUpdate: api.update,
  refresh: () => $table.value?.handleSearch(),
})

function onFinish({ event }, key) {
  const result = JSON.parse(event.target.response)
  modalForm.value[key] = `${modalForm.value[key]},${result.data.imgUrl}`.split(',').filter(Boolean).toString()
}

function onRemove({ fileList, index }, key) {
  const files = [...fileList]
  files.splice(index, 1);
  modalForm.value[key] = files.map(i => i.id).toString();
  return true;
}

// async function handleEnable(row) {
//   row.enableLoading = true
//   try {
//     await api.update({ id: row.id, enable: !row.enable })
//     row.enableLoading = false
//     $message.success('操作成功')
//     $table.value?.handleSearch()
//   } catch (error) {
//     row.enableLoading = false
//   }
// }

function onBeforeUpload({ file }) {
  const size = file.file.size / 1024 / 1024
  if (size <= 2) return true
  $message.warning('请上传2M以内的图片')
  return false
}

function handleOpenRolesSet(row) {
  handleOpen({
    action: 'setRole',
    title: '设置审核状态',
    row,
    onOk: onSave,
  })
}

function onSave() {
  if (modalAction.value === 'setRole') {
    return handleSave({
      api: () => api.update(modalForm.value),
      cb: () => $message.success('设置成功'),
    })
  } else if (modalAction.value === 'setGoods') {
    return handleSave({
      api: () => api.update(modalForm.value),
      cb: () => $message.success('商品修改成功'),
    })
  }
  handleSave()
}

const columns = genColumns({ handleOpenRolesSet, handleOpen, handleDelete, onSave, h })

const columnFields = computed(() => columns.filter((col) => col.isTable))
const formFields = computed(() =>
  columns.filter((col) =>
    modalAction.value === 'setRole'
      ? col.isSetRole
      : modalAction.value === 'reset'
        ? col.isResetPwd
        : col.isForm
  )
)
</script>
